#!/usr/bin/env sh

# Script to deploy certificates to Ali CDN

# The following variables exported from environment will be used.
# If not set then values previously saved in domain.conf file are used.
#
#
# export DEPLOY_ALI_CDN_ID=""  # access key id
# export DEPLOY_ALI_CDN_SECRET=""  # access key secret
# export DEPLOY_ALI_CDN_DOMAINS=""  # domains, used for SAN or wildcard certificate 

########  Public functions #####################
ali_cdn_deploy() {
  _cdomain="$1"
  _ckey="$2"
  _ccert="$3"
  _cca="$4"
  _cfullchain="$5"

  _debug _cdomain "$_cdomain"
  _debug _ckey "$_ckey"
  _debug _ccert "$_ccert"
  _debug _cca "$_cca"
  _debug _cfullchain "$_cfullchain"

  # access key id is required to access Ali api. 
  _migratedeployconf Le_Deploy_ali_cdn_id DEPLOY_ALI_CDN_ID
  _getdeployconf DEPLOY_ALI_CDN_ID
  _debug2 DEPLOY_ALI_CDN_ID "$DEPLOY_ALI_CDN_ID"
  if [ -z "$DEPLOY_ALI_CDN_ID" ]; then
    _err "DEPLOY_ALI_CDN_ID not defined."
    return 1
  fi
  _savedeployconf DEPLOY_ALI_CDN_ID "$DEPLOY_ALI_CDN_ID" 

  # access key secret is required to access Ali api. 
  _migratedeployconf Le_Deploy_ali_cdn_secret DEPLOY_ALI_CDN_SECRET
  _getdeployconf DEPLOY_ALI_CDN_SECRET
  _debug2 DEPLOY_ALI_CDN_SECRET "$DEPLOY_ALI_CDN_SECRET"
  if [ -z "$DEPLOY_ALI_CDN_SECRET" ]; then
    _err "DEPLOY_ALI_CDN_SECRET not defined."
    return 1
  fi
  _savedeployconf DEPLOY_ALI_CDN_SECRET "$DEPLOY_ALI_CDN_SECRET" 

  # domain names is required when deploy SAN or wildcard cert. 
  _migratedeployconf Le_Deploy_ali_cdn_domains DEPLOY_ALI_CDN_DOMAINS
  _getdeployconf DEPLOY_ALI_CDN_DOMAINS
  _debug2 DEPLOY_ALI_CDN_DOMAINS "$DEPLOY_ALI_CDN_DOMAINS"
  if [ -z "$DEPLOY_ALI_CDN_DOMAINS" ]; then
    DEPLOY_ALI_CDN_DOMAINS=$_cdomain
  fi
    
  _adomains="`echo $DEPLOY_ALI_CDN_DOMAINS`"
  _savedeployconf DEPLOY_ALI_CDN_DOMAINS "$DEPLOY_ALI_CDN_DOMAINS" 

  # deploy 
  _ali_cdn_deploy

  _err_code="$?"
  return $_err_code
}

_ali_cdn_deploy() {

  aliyun configure set --profile akProfile --mode AK --region cn-hangzhou \
  --access-key-id "$DEPLOY_ALI_CDN_ID" \
  --access-key-secret "$DEPLOY_ALI_CDN_SECRET"

  cert=`cat "$_cfullchain"`                               
  key=`cat "$_ckey"`
  aliyun cdn BatchSetCdnDomainServerCertificate --region cn-hangzhou \
  --DomainName "$_adomains" --SSLProtocol on --CertType upload \
  --SSLPub="$cert" \
  --SSLPri="$key" \
  --ForceSet 1

  _err_code="$?"
  if [ "$_err_code" -ne 0 ];then
    return $_err_code
  fi

  aliyun configure delete --profile akProfile 

  return 0 
}  
